package ecs

import "fmt"

type engine struct {
	entityManager *EntityManager
	systemManager *SystemManager
}

func NewEngine(entityManager *EntityManager, systemManager *SystemManager) *engine {
	return &engine{
		entityManager: entityManager,
		systemManager: systemManager,
	}
}

func (e *engine) Tick() (stop bool, err error) {
	defer func() {
		e := recover()
		if e != nil {
			err = fmt.Errorf("%v", e)
		}
	}()
	shouldStop := false
	for _, system := range e.systemManager.Systems() {
		state, err := system.Process(e.entityManager)
		if err != nil {
			return true, err
		}
		if state == true {
			shouldStop = true
			break
		}
	}
	return shouldStop, nil
}

func (e *engine) Setup() {
	for _, sys := range e.systemManager.Systems() {
		sys.Setup()
	}
}

func (e *engine) Teardown() {
	for _, sys := range e.systemManager.Systems() {
		sys.Teardown()
	}
}
